/*
 * The MIT License
 *
 * Copyright 2011 Edwin Bratini <edwin.bratini@gmail.com>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*
 * BusquedaRapida.java
 *
 * Created on Nov 9, 2011, 4:32:38 PM
 */
package org.salvador_dali.psychsys.ui;

import java.awt.Color;
import java.awt.Frame;
import java.awt.event.KeyEvent;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.salvador_dali.psychsys.ui.EntitySearcher;
import org.salvador_dali.psychsys.business.validators.NumberFieldValidator;

/**
 *
 * @author Edwin Bratini <edwin.bratini@gmail.com>
 */
public class BusquedaRapida extends javax.swing.JDialog {

    private Object entitySelectedId;
    private EntitySearcher entitySearcher;

    /** Creates new form BusquedaRapida */
    public BusquedaRapida(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        getRootPane().setDefaultButton(btnBuscar);
    }

    public BusquedaRapida(EntitySearcher entitySearcher, Frame owner, boolean modal) {
        super(owner, modal);
        this.entitySearcher = entitySearcher;
        //initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblProgressBar = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        pnlOpBusqueda = new javax.swing.JPanel();
        cmbCampoBuscar = new javax.swing.JComboBox();
        lblEntidades = new javax.swing.JLabel();
        scrEntidades = new javax.swing.JScrollPane();
        tblEntidades = new javax.swing.JTable();
        btnBuscar = new javax.swing.JButton();
        txtBusqueda = new javax.swing.JTextField();
        btnSeleccionar = new javax.swing.JButton();
        statusPanel2 = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator2 = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel2 = new javax.swing.JLabel();

        lblProgressBar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/circle progress bar 20x20.png"))); // NOI18N

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Busqueda de Estudiantes");
        setModal(true);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        pnlOpBusqueda.setBorder(javax.swing.BorderFactory.createTitledBorder("Opciones de Busqueda"));
        pnlOpBusqueda.setName("pnlOpBusqueda"); // NOI18N

        cmbCampoBuscar.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Id", "Nombre", "Apellido" }));

        javax.swing.GroupLayout pnlOpBusquedaLayout = new javax.swing.GroupLayout(pnlOpBusqueda);
        pnlOpBusqueda.setLayout(pnlOpBusquedaLayout);
        pnlOpBusquedaLayout.setHorizontalGroup(
            pnlOpBusquedaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlOpBusquedaLayout.createSequentialGroup()
                .addComponent(cmbCampoBuscar, 0, 163, Short.MAX_VALUE)
                .addContainerGap())
        );
        pnlOpBusquedaLayout.setVerticalGroup(
            pnlOpBusquedaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlOpBusquedaLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(cmbCampoBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        lblEntidades.setText("Estudiantes");

        scrEntidades.setAutoscrolls(true);
        scrEntidades.setName("scrEntidades"); // NOI18N

        tblEntidades.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"2010-10", "Bratini G., Edwin A.", "4to de Media"},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Id", "Nombre", "Curso"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblEntidades.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblEntidadesMouseClicked(evt);
            }
        });
        scrEntidades.setViewportView(tblEntidades);

        btnBuscar.setText("Buscar");
        btnBuscar.setName("btnBuscar"); // NOI18N
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        txtBusqueda.setName("txtBusqueda"); // NOI18N
        txtBusqueda.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtBusquedaKeyPressed(evt);
            }
        });

        btnSeleccionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/ok.png"))); // NOI18N
        btnSeleccionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSeleccionarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(pnlOpBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(txtBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 376, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(btnBuscar))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                            .addComponent(lblEntidades)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnSeleccionar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(scrEntidades, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnBuscar))
                    .addComponent(pnlOpBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnSeleccionar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblEntidades))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scrEntidades, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        statusMessageLabel.setForeground(new java.awt.Color(0, 153, 51));

        statusAnimationLabel2.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/circle progress bar 20x20.png"))); // NOI18N

        javax.swing.GroupLayout statusPanel2Layout = new javax.swing.GroupLayout(statusPanel2);
        statusPanel2.setLayout(statusPanel2Layout);
        statusPanel2Layout.setHorizontalGroup(
            statusPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 662, Short.MAX_VALUE)
            .addGroup(statusPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 622, Short.MAX_VALUE)
                .addComponent(statusAnimationLabel2)
                .addContainerGap())
        );
        statusPanel2Layout.setVerticalGroup(
            statusPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanel2Layout.createSequentialGroup()
                .addComponent(statusPanelSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(statusPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel2))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
                .addComponent(statusPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public EntitySearcher getEntitySearcher() {
        return entitySearcher;
    }

    public void setEntitySearcher(EntitySearcher entitySearcher) {
        this.entitySearcher = entitySearcher;
    }
    
    public void setEntitySearcher(org.salvador_dali.psychsys.business.EntitySearcher entitySearcher) {
        throw new UnsupportedOperationException();
    }

    public Object getEntitySelectedId() {
        return entitySelectedId;
    }

    public void setEntitySelectedId(Object entitySelectedId) {
        this.entitySelectedId = entitySelectedId;
    }

    public JLabel getLblEntidades() {
        return lblEntidades;
    }

    public void setLblEntidades(JLabel lblEntidades) {
        this.lblEntidades = lblEntidades;
    }

private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
    // TODO add your handling code here:
    if (txtBusqueda.getText().isEmpty()) {
        JOptionPane.showMessageDialog(this, "Introduzca texto a buscar", "Busqueda", JOptionPane.ERROR_MESSAGE);
        return;
    }
    doSearch();
}//GEN-LAST:event_btnBuscarActionPerformed

private void txtBusquedaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBusquedaKeyPressed
    // TODO add your handling code here:
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        btnBuscar.doClick();
    }
}//GEN-LAST:event_txtBusquedaKeyPressed

private void btnSeleccionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSeleccionarActionPerformed
    // TODO add your handling code here:
    if (tblEntidades.getSelectedRow() == -1) {
        JOptionPane.showMessageDialog(this, "Primero seleccione registro", "Seleccion", JOptionPane.ERROR_MESSAGE);
        return;
    }
    entitySelectedId = tblEntidades.getValueAt(tblEntidades.getSelectedRow(), 0);
    this.dispose();
}//GEN-LAST:event_btnSeleccionarActionPerformed

    private void tblEntidadesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblEntidadesMouseClicked
        // TODO add your handling code here:
        if (evt.getClickCount() == 2) {
            btnSeleccionar.doClick();
        }
    }//GEN-LAST:event_tblEntidadesMouseClicked

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        // customizando el jtable y evitando que puedan mover las columnas
        /*if (entitySearcher != null) {
            cmbCampoBuscar.setModel(entitySearcher.getDefComboBoxModel());
            tblEntidades.setColumnModel(entitySearcher.getDefTableColumnModel());
            tblEntidades.setModel(entitySearcher.getDefTableModel());
        } else {
            tblEntidades.setColumnModel(new DefaultTableColumnModel() {

                @Override
                public void moveColumn(int columnIndex, int newIndex) {
                    if (columnIndex == 0 || newIndex == 0) {
                        return;
                    }
                    super.moveColumn(columnIndex, newIndex);
                }
            });

            DefaultTableModel dtm = new DefaultTableModel(new Object[][]{{}},
                    new Object[]{"Id", "Col 2", "Col 3"}) {

                @Override
                public boolean isCellEditable(int rowIndex, int mColIndex) {
                    return false;
                }                
            };

            tblEntidades.setModel(dtm);
        }*/
        if (entitySearcher != null) {
            cmbCampoBuscar.setModel(new DefaultComboBoxModel(entitySearcher.getFieldsToSearch().toArray()));
            tblEntidades.setColumnModel(entitySearcher.getDefTableColumnModel());
            tblEntidades.setModel(entitySearcher.getDefTableModel());
        } else {
            tblEntidades.setColumnModel(new DefaultTableColumnModel() {

                @Override
                public void moveColumn(int columnIndex, int newIndex) {
                    if (columnIndex == 0 || newIndex == 0) {
                        return;
                    }
                    super.moveColumn(columnIndex, newIndex);
                }
            });

            DefaultTableModel dtm = new DefaultTableModel(new Object[][]{{}},
                    new Object[]{"Id", "Col 2", "Col 3"}) {

                @Override
                public boolean isCellEditable(int rowIndex, int mColIndex) {
                    return false;
                }                
            };

            tblEntidades.setModel(dtm);
        }
    }//GEN-LAST:event_formWindowOpened

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BusquedaRapida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BusquedaRapida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BusquedaRapida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BusquedaRapida.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                BusquedaRapida dialog = new BusquedaRapida(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    private void doSearch() {
        if (cmbCampoBuscar.getSelectedItem().toString().equalsIgnoreCase("id") && !txtBusqueda.getText().equals("*")) {
            if (!new NumberFieldValidator().validate(txtBusqueda.getText())) {
                JOptionPane.showMessageDialog(this, "Este campo solo acepta numeros", "Busqueda", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
        entitySearcher.doSearch(cmbCampoBuscar.getSelectedItem().toString(), txtBusqueda.getText());
        //TableModel tm = getEntitySearcher().doSearch(cmbCampoBuscar.getSelectedItem().toString(), txtBusqueda.getText());
        TableModel tm = entitySearcher.getTableModelFromSearch();
        if (tm != null) {
            tblEntidades.setModel(tm);
            tblEntidades.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        } else {
            statusMessageLabel.setText("No hubo resultados");
            statusMessageLabel.setForeground(Color.red);
            new Thread(new LabelToolTipShower(statusMessageLabel, 3000)).start();
            tblEntidades.setModel(getEntitySearcher().getDefTableModel());
            return;
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnSeleccionar;
    private javax.swing.JComboBox cmbCampoBuscar;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblEntidades;
    private javax.swing.JLabel lblProgressBar;
    private javax.swing.JPanel pnlOpBusqueda;
    private javax.swing.JScrollPane scrEntidades;
    private javax.swing.JLabel statusAnimationLabel2;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel2;
    private javax.swing.JTable tblEntidades;
    private javax.swing.JTextField txtBusqueda;
    // End of variables declaration//GEN-END:variables
}
